package cn.scut.post.service.impl;

import cn.scut.post.dao.PostCollectDao;
import cn.scut.post.dao.PostInfoDao;
import cn.scut.post.pojo.Collect;
import cn.scut.post.pojo.Post;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PostCollectService extends ServiceImpl<PostCollectDao, Collect> {
    PostCollectDao postCollectDao;
    PostInfoDao postInfoDao;

    public Post collectPost(String postid, String openid) {
        int i = postCollectDao.selectOneCollect(postid, openid);
        // 没有收藏过
        if (i == 0) {
            Post post = postInfoDao.selectByPostid(postid);
            // 有无相关帖子的存在（前端收藏可以保证存在）
            if (post != null) {
                postCollectDao.insertUserCollect(new Collect(postid, openid));
            } else {
                return null;
            }
        }
        // 已经收藏过了
        return postInfoDao.selectByPostid(postid);
    }

    public List<Post> getUserCollect(String openid) {
        List<Collect> collects = postCollectDao.selectAllCollect(openid);
        if (collects != null) {
            List<Post> ans = new ArrayList<>();
            for (Collect collect : collects) {
                //System.out.println(collect);
                Post post = postInfoDao.selectByPostid(collect.getPostid());
                ans.add(post);
            }
            return ans;
        } else {
            return null;
        }
    }

    public Post deleteUserCollect(String postid, String openid) {
        int i = postCollectDao.selectOneCollect(postid, openid);
        if (i == 0) {
            return null;
        }
        Post post = postInfoDao.selectByPostid(postid);
        postCollectDao.deleteUserCollect(postid, openid);
        return post;
    }

    @Autowired
    public void setPostCollectionDao(PostCollectDao postCollectDao) {
        this.postCollectDao = postCollectDao;
    }

    @Autowired
    public void setPostInfoDao(PostInfoDao postInfoDao) {
        this.postInfoDao = postInfoDao;
    }
}
